#!/bin/bash

# MySQL MCP Server 诊断脚本
# 用于自动检测和诊断常见问题

echo "=== MySQL MCP Server 诊断工具 ==="
echo "正在检查系统配置和常见问题..."
echo ""

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查函数
check_ok() {
    echo -e "${GREEN}✓ $1${NC}"
}

check_warn() {
    echo -e "${YELLOW}⚠ $1${NC}"
}

check_error() {
    echo -e "${RED}✗ $1${NC}"
}

# 1. 检查 Go 环境
echo "1. 检查 Go 环境..."
if command -v go &> /dev/null; then
    GO_VERSION=$(go version)
    check_ok "Go 已安装: $GO_VERSION"
else
    check_error "Go 未安装或不在 PATH 中"
fi
echo ""

# 2. 检查项目文件
echo "2. 检查项目文件..."
if [ -f "../src/main.go" ]; then
    check_ok "main.go 存在"
else
    check_error "main.go 不存在"
fi

if [ -f "../src/go.mod" ]; then
    check_ok "go.mod 存在"
else
    check_error "go.mod 不存在"
fi

if [ -f "../bin/mysql-mcp-server" ]; then
    check_ok "mysql-mcp-server 可执行文件存在"
    if [ -x "../bin/mysql-mcp-server" ]; then
        check_ok "mysql-mcp-server 有执行权限"
    else
        check_warn "mysql-mcp-server 没有执行权限，正在修复..."
        chmod +x ../bin/mysql-mcp-server
        check_ok "执行权限已修复"
    fi
else
    check_warn "mysql-mcp-server 可执行文件不存在，尝试构建..."
    if (cd ../src && go build -o ../bin/mysql-mcp-server); then
        check_ok "成功构建 mysql-mcp-server"
    else
        check_error "构建失败"
    fi
fi
echo ""

# 3. 检查依赖项
echo "3. 检查 Go 依赖项..."
if (cd ../src && go mod verify) &> /dev/null; then
    check_ok "Go 模块验证通过"
else
    check_warn "Go 模块验证失败，尝试修复..."
    (cd ../src && go mod download && go mod tidy)
    check_ok "依赖项已更新"
fi
echo ""

# 4. 检查环境变量
echo "4. 检查环境变量..."
required_vars=("MYSQL_USER" "MYSQL_DATABASE")
optional_vars=("MYSQL_HOST" "MYSQL_PORT" "MYSQL_PASSWORD")

for var in "${required_vars[@]}"; do
    if [ -z "${!var}" ]; then
        check_error "$var 环境变量未设置（必需）"
    else
        check_ok "$var 已设置: ${!var}"
    fi
done

for var in "${optional_vars[@]}"; do
    if [ -z "${!var}" ]; then
        check_warn "$var 环境变量未设置（可选，将使用默认值）"
    else
        check_ok "$var 已设置"
    fi
done
echo ""

# 5. 检查 MySQL 连接
echo "5. 检查 MySQL 连接..."
MYSQL_HOST=${MYSQL_HOST:-localhost}
MYSQL_PORT=${MYSQL_PORT:-3306}
MYSQL_USER=${MYSQL_USER:-root}
MYSQL_DATABASE=${MYSQL_DATABASE:-test}

if command -v mysql &> /dev/null; then
    if [ -n "$MYSQL_PASSWORD" ]; then
        if mysql -h "$MYSQL_HOST" -P "$MYSQL_PORT" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "USE $MYSQL_DATABASE;" 2>/dev/null; then
            check_ok "MySQL 数据库连接成功"
        else
            check_error "MySQL 数据库连接失败"
            echo "  请检查以下配置："
            echo "  - 主机: $MYSQL_HOST"
            echo "  - 端口: $MYSQL_PORT"
            echo "  - 用户: $MYSQL_USER"
            echo "  - 数据库: $MYSQL_DATABASE"
        fi
    else
        check_warn "MYSQL_PASSWORD 未设置，跳过数据库连接测试"
    fi
else
    check_warn "mysql 客户端未安装，跳过连接测试"
fi
echo ""

# 6. 运行单元测试
echo "6. 运行单元测试..."
if (cd ../src && go test -short -v 2>/dev/null) | grep -q "PASS"; then
    check_ok "单元测试通过"
else
    check_warn "单元测试失败或跳过"
fi
echo ""

# 7. 检查配置文件
echo "7. 检查配置文件..."
if [ -f "../config/claude_desktop_config.json" ]; then
    check_ok "配置文件存在: claude_desktop_config.json"
    if python3 -m json.tool ../config/claude_desktop_config.json > /dev/null 2>&1; then
        check_ok "配置文件 JSON 格式有效"
    else
        check_error "配置文件 JSON 格式无效"
    fi
else
    check_warn "配置文件不存在，可以运行配置脚本生成"
fi
echo ""

# 8. 检查端口占用
echo "8. 检查端口占用..."
if command -v netstat &> /dev/null; then
    if netstat -an | grep -q ":$MYSQL_PORT "; then
        check_ok "MySQL 端口 $MYSQL_PORT 正在使用"
    else
        check_warn "MySQL 端口 $MYSQL_PORT 未在使用"
    fi
else
    check_warn "netstat 不可用，跳过端口检查"
fi
echo ""

# 9. 生成诊断报告
echo "9. 生成诊断报告..."
{
    echo "MySQL MCP Server 诊断报告"
    echo "生成时间: $(date)"
    echo ""
    echo "系统信息:"
    echo "  操作系统: $(uname -s) $(uname -r)"
    echo "  架构: $(uname -m)"
    if command -v go &> /dev/null; then
        echo "  Go 版本: $(go version)"
    fi
    echo ""
    echo "配置:"
    echo "  MYSQL_HOST: ${MYSQL_HOST:-未设置}"
    echo "  MYSQL_PORT: ${MYSQL_PORT:-未设置}"
    echo "  MYSQL_USER: ${MYSQL_USER:-未设置}"
    echo "  MYSQL_DATABASE: ${MYSQL_DATABASE:-未设置}"
    echo "  MYSQL_PASSWORD: ${MYSQL_PASSWORD:+已设置}"
    echo ""
    echo "文件状态:"
    echo "  main.go: $([ -f ../src/main.go ] && echo '存在' || echo '不存在')"
    echo "  go.mod: $([ -f ../src/go.mod ] && echo '存在' || echo '不存在')"
    echo "  mysql-mcp-server: $([ -f ../bin/mysql-mcp-server ] && echo '存在' || echo '不存在')"
    echo "  配置文件: $([ -f ../config/claude_desktop_config.json ] && echo '存在' || echo '不存在')"
} > diagnosis_report.txt

check_ok "诊断报告已保存到 diagnosis_report.txt"
echo ""

# 10. 建议修复步骤
echo "10. 建议的修复步骤..."
echo ""
echo "如果遇到问题，请按以下顺序尝试解决："
echo ""
echo "a) 设置必需的环境变量:"
echo "   export MYSQL_USER=your_username"
echo "   export MYSQL_DATABASE=your_database"
echo "   export MYSQL_PASSWORD=your_password"
echo ""
echo "b) 构建服务器:"
echo "   go mod download"
echo "   go build -o mysql-mcp-server"
echo ""
echo "c) 测试服务器:"
echo "   ./mysql-mcp-server"
echo ""
echo "d) 生成配置文件:"
echo "   go run test_mcp.go config"
echo ""
echo "e) 运行调试模式:"
echo "   go run debug_server.go"
echo ""

echo "=== 诊断完成 ==="
echo "详细报告已保存到 diagnosis_report.txt"
echo "如需更多帮助，请查看 TROUBLESHOOTING.md" 